import {Component, OnInit} from '@angular/core';
import {HttpRequest, HttpClient, HttpEventType, HttpEvent, HttpResponse} from '@angular/common/http';
import {NzMessageService, UploadXHRArgs} from 'ng-zorro-antd';

import * as C from '../../../../global/config';

@Component({
  selector: 'app-tool-icon-generator',
  templateUrl: './ico-generator.component.html',
  styleUrls: ['./ico-generator.component.css']
})
export class IcoGeneratorComponent implements OnInit {

  radioValue = '16';

  constructor(private http: HttpClient,
              private msg: NzMessageService) {
  }

  ngOnInit() {
    document.getElementById('page-item-name').innerText = 'ico生成器';
  }

  handleChange({file}): void {
    if (file.status === 'done') {
      console.log(file);
      this.msg.success(`${file.name} 上传成功`);
      this.download(`download/ico/${file.response.data}`);
    } else if (file.status === 'error') {
      this.msg.error(`${file.name} 上传失败`);
    }
  }

  download(url) {
    const form = document.createElement('form');
    form.style.display = 'none';
    form.setAttribute('target', 'fraSubmit');
    form.setAttribute('method', 'get');
    form.setAttribute('action', `${C.basePath}/${url}`);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
  }

  icoUpload = (item: UploadXHRArgs) => {
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    formData.append('file', item.file as any);
    formData.append('size', this.radioValue);
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress: true,
      withCredentials: true
    });
    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          (event as any).percent = event.loaded / event.total * 100;
        }
        // 处理上传进度条，必须指定 `percent` 属性来表示进度
        item.onProgress(event, item.file);
      } else if (event instanceof HttpResponse) {
        // 处理成功
        item.onSuccess(event.body, item.file, event);
      }
    }, (err) => {
      // 处理失败
      item.onError(err, item.file);
    });
  };

}
